//
//  HomeViewController.m
//  KEREN
//
//  Created by MW on 2023/3/10.
//
#import "HomeViewController.h"
#import "DeviceSettingViewController.h"
#import "ScanDeviceViewController.h"
#import "HomeBottomView.h"
#import "DeviceInfo.h"
#import "GarageManagmentVC.h"
#import "KRGarageViewController.h"
#import "KRXKAlartView.h"
#import "KRXKTipsAlertView.h"
#import "KRWeatherView.h"
#import "NSDictionary+Expand.h"
#import "KRTabarController.h"
@interface HomeViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) HomeBottomView *bottomView;
@property (nonatomic, strong) UILabel *deviceNameLbl;
@property (nonatomic, strong) UIView *pointView;
@property (nonatomic, strong) UIView *bleStatusPoint;
@property (nonatomic, strong) UIScrollView *scollView;
@property (nonatomic, assign) int currentIndex; //当前滑动到第几辆车
@property (nonatomic, strong) UIButton *xiaokeBtn;
@property (nonatomic, strong) UIButton *device_NextBtn;
@property (nonatomic, strong) UIButton *device_LastBtn;
@property (nonatomic, strong) UIView *noticeView;
@property (nonatomic, strong) KRWeatherView *weatherV;
@property (nonatomic, assign) BOOL gps_status;
@property (nonatomic, strong) UIImageView *elementimageView;
@property (nonatomic, strong) UIView *percentageView;//w：25代表100%🔋
@property (nonatomic, strong) UILabel *percentageLbl;
@property (nonatomic, assign) BOOL isNavBarShow;
@property (nonatomic, assign) BOOL isAnimate;
@property (nonatomic, assign) BOOL isShowMessgeNoticeView;
@property (nonatomic, strong) UIImageView *logo;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *setBtn;
@property (nonatomic, strong) DeviceInfo *currentDeviceInfo;
@property (nonatomic, strong) KRXKAlartView *layerView;
@property (nonatomic, strong) KRXKTipsAlertView *alertView;
@property (nonatomic, strong) NSString *alertStr;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation HomeViewController
#pragma mark- Lazy load
- (HomeBottomView *)bottomView{
    if(!_bottomView){
        _bottomView = [[HomeBottomView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT - 220, DEVICE_WIDTH, 220)];
        [self.view addSubview:_bottomView];
        _xiaokeBtn = [UIButton setButtonWithImage:@"xiaoke_icon" cornerRadius:0 backColor:[UIColor clearColor]];
        [self.view addSubview:_xiaokeBtn];
        _xiaokeBtn.frame = CGRectMake(DEVICE_WIDTH - 72 - 24, DEVICE_HEIGHT - 220 - 82, 72, 72);
        [_xiaokeBtn addTarget:self action:@selector(xiaokeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addKRXKTipsAlertView:@"欢迎使用可人APP"];
    }
    return _bottomView;
}

- (UIView *)noticeView{
    if(!_noticeView){
        _noticeView = [[KRAlartManager shareInstance] showMessgeNoticeView];
    }
    return _noticeView;
}

-(NSTimer *)timer{
    if(!_timer){
        WEAKSELF
        _timer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {
            if(ISLOGIN){
                AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
                if(netManger.networkReachabilityStatus != AFNetworkReachabilityStatusNotReachable){
                    [weakSelf getDevicesharelist];
                }
            }
        }];
    }
    return _timer;
}

#pragma mark- lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    _isNavBarShow = NO;
    [self setViewLayout];
    [self bottomView];
    [self.view addSubview:[self navBottomViewTag:0]];
    self.navBottomView.frame = CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, 70);
    _currentIndex = 0;

    WEAKSELF
    //获取天气 气温 风速
    [[GDMapTool sharedInstance] getCurrentLocation:^{
        NSAttributedString *showAttString = [NSAttributedString getAttributeWith:@[WEATHER] string:[NSString stringWithFormat:@"当前天气 %@",WEATHER] Font:Font(12) Color:Color_AAAAAA attributeFont:BFont(12) attributeColor:Color_DDDDDD];
        weakSelf.weatherV.weatherLbl.attributedText = showAttString;
        
        NSAttributedString *tAttString = [NSAttributedString getAttributeWith:@[TEMPERATURE] string:[NSString stringWithFormat:@"气温 %@°C",TEMPERATURE] Font:Font(12) Color:Color_AAAAAA attributeFont:BFont(12) attributeColor:Color_DDDDDD];
        weakSelf.weatherV.temperatureLbl.attributedText = tAttString;
        
        NSAttributedString *attString = [NSAttributedString getAttributeWith:@[WINDPOWER] string:[NSString stringWithFormat:@"风速 %@",WINDPOWER] Font:Font(12) Color:Color_AAAAAA attributeFont:BFont(12) attributeColor:Color_DDDDDD];
        weakSelf.weatherV.windpowerLbl.attributedText = attString;
    }];
    BOOL isNotFirstLoding = [[NSUserDefaults standardUserDefaults] boolForKey:IS_NOTFIRST_LODINGHOMEVC];
    if(!isNotFirstLoding){
        [self backImageClick];
        [[KRAlartManager shareInstance] showFirstuseApp];
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateCurrentDevice) name:@"UPDATECURRENTDEVICE" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blueVerifySuccess) name:BLUETOOTHVERIFYSUCCESS object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blueToothDisconnect:) name:BLUETOOTHDISCONNECTED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blueToothDisconnect:) name:BlueToothStatePoweredOff object:nil];
    AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
    [netManger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status != AFNetworkReachabilityStatusNotReachable && self.deviceInfoList.count == 0 && ISLOGIN){
            DDLogInfo(@"============statusChangeBlock  requsetDeviceInfoList ");
            [weakSelf requsetDeviceInfoList];
        }
    }];
    [netManger startMonitoring];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UserInfo *user = USERINFO;
    if(user.token.length > 0){
        [self requsetDeviceInfoList];
        [self getDevicesharelist];
        [self timer];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if(_layerView){
        [_layerView removeFromSuperview];
        _layerView = nil;
    }
}

#pragma mark- NetQuery
- (void)getDeviceStatus{
    if(_currentDeviceInfo.Id == 0){
        NSLog(@"=======currentDeviceInfo id is 0");
        return;
    }
    WEAKSELF
    [NetworkingTool POST:Get_Device_status parameters:@{@"ebike_id":@(_currentDeviceInfo.Id)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        weakSelf.currentDeviceInfo.lock_status = [response[@"data"][@"lock_status"] intValue];
        weakSelf.currentDeviceInfo.power_status = [response[@"data"][@"power_status"] intValue];
        weakSelf.currentDeviceInfo.online_status = [response[@"data"][@"online_status"] intValue];
        [UserInfoManager sharedInstance].currentDeviceInfo.lock_status = weakSelf.currentDeviceInfo.lock_status;
        [UserInfoManager sharedInstance].currentDeviceInfo.online_status = weakSelf.currentDeviceInfo.online_status;
        [UserInfoManager sharedInstance].currentDeviceInfo.power_status = weakSelf.currentDeviceInfo.power_status;
        [weakSelf showOnlineAndBLEStatusUI];
        if([UserInfoManager sharedInstance].currentDeviceInfo.online_status == 1){
            [weakSelf getDeviceBattery];
            if(weakSelf.currentDeviceInfo.is_manager && [UserInfoManager sharedInstance].currentDeviceInfo.power_status == 0){
                [KeRenRequestTool otaCheckVersionAndUpgrade:weakSelf.currentDeviceInfo];
            }
            if(weakSelf.currentDeviceInfo.is_manager){
                [weakSelf getmessageNotifyList];
            }
        }else{
            [weakSelf showBatteryUI:NO];
        }
        [weakSelf.bottomView setPower_status:YES];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)getDeviceBattery{
    WEAKSELF
    if([UserInfoManager sharedInstance].currentDeviceInfo.Id > 0){
        [NetworkingTool POST:Device_location parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"cmd":@"Battery"} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                int soc = [response[@"data"][@"soc"] intValue];
                [weakSelf showSocUI:soc];
            }else{
                [weakSelf showBatteryUI:NO];
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }
}

- (void)requsetDeviceInfoList{
    NSLog(@"======requsetDeviceInfoList");
    WEAKSELF
    [NetworkingTool POST:Device_list parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf.deviceInfoList removeAllObjects];
        [[UserInfoManager sharedInstance].deviceInfoList removeAllObjects];
        if(response[@"data"] && [response[@"data"] isKindOfClass:[NSArray class]]){
            NSArray *dataArr = response[@"data"];
            for (int i = 0; i < dataArr.count; i++) {
                NSDictionary *dict = dataArr[i];
                DeviceInfo *deviceInfo = [DeviceInfo initWithDictionary:dict];
               // deviceInfo.socket_type = 0;
                [weakSelf.deviceInfoList addObject:deviceInfo];
            }
            [UserInfoManager sharedInstance].deviceInfoList = weakSelf.deviceInfoList;
        }
        [weakSelf updateScollView];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(UIViewController *)findVCInNav:(NSString *)vcName{
    NSArray *array = self.navigationController.viewControllers;
    for(UIViewController *vc in array){
        if([vc isKindOfClass:NSClassFromString(vcName)]){
            return vc;
        }
    }
    return nil;
}


- (void)getDevicesharelist{
    WEAKSELF
    NSDictionary *parameters = @{@"type":@(1)};
    [NetworkingTool POST:Device_share_list parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            NSDictionary *data = [response dictForDict:@"data"];
            NSArray *arr = [data arrayForDict:@"list"];
            
            for (int i = 0; i < arr.count; i ++) {
                NSDictionary *dict = arr[i];
                if([dict[@"status"] intValue] == 1){
                    [weakSelf showMessgeNoticeView];
                    break;
                }
                if(i == arr.count - 1){
                    weakSelf.isShowMessgeNoticeView = NO;
                    [weakSelf.elementimageView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(weakSelf.weatherV.mas_bottom).offset(17);
                    }];
                    [weakSelf.noticeView removeAllSubviews];
                    [weakSelf.noticeView removeFromSuperview];
                    weakSelf.noticeView = nil;
                }
            }
            
            NSMutableArray *removeArrayInList = @[].mutableCopy;
            if(arr.count == 0){
                for(DeviceInfo *device in weakSelf.deviceInfoList){
                    if(device.is_manager == 0){
                        [removeArrayInList addObject:device];
                    }
                }
            }else{
                for(DeviceInfo *device in weakSelf.deviceInfoList){
                    if(device.is_manager == 0){
                        BOOL find = NO;
                        for(int i= 0; i< arr.count; i++){
                            NSDictionary *dict = arr[i];
                            NSInteger ebike_id = [dict intForDict:@"ebike_id"];
                            if(ebike_id == device.Id){
                                find = YES;
                                break;
                            }
                        }
                        if(!find){
                            [removeArrayInList addObject:device];
                        }
                    }
                }
            }

            if(removeArrayInList.count > 0){
                [weakSelf.deviceInfoList removeObjectsInArray:removeArrayInList];
                NSInteger index = [weakSelf.deviceInfoList indexOfObject:weakSelf.currentDeviceInfo];
                if(index != NSNotFound){
                    weakSelf.currentIndex = index;
                }else{
                    weakSelf.currentIndex = 0;
                    UIViewController *tabC = [weakSelf findVCInNav:@"KRTabarController"];
                    UIViewController *topV = weakSelf.navigationController.topViewController;
                    if(![topV isKindOfClass:[KRTabarController class]]){
                        [weakSelf.navigationController popToViewController:tabC animated:YES];
                    }
                }
                [weakSelf updateScollView];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}
- (void)getmessageNotifyList{
    WEAKSELF
    NSDictionary *parameters = @{@"index":@(1),@"size":@(20),@"message_type":@(1),@"ebike_id":@(_currentDeviceInfo.Id)};
    [NetworkingTool POST:@"/v1/app/messageNotify/list" parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(response[@"data"] && [response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                NSArray *arr = response[@"data"][@"list"];
                if(arr.count > 0){
                    [weakSelf addKRXKTipsAlertView:@"车辆存在故障，请检查"];
                }
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
    }];
}


#pragma mark- BLEQuery
-(void)bleQueryData{
    NSLog(@"=======HomeViewController bleQueryData");
    WEAKSELF
    [self showOnlineAndBLEStatusUI];
    if(![self.currentDeviceInfo is4GDevice]){
        [self.bottomView setPower_status:NO];
        if(self.currentDeviceInfo.battery_type == 1){
            [HABleManager bleQueryElectrictStatus:^(HABleModel * _Nonnull bleModel) {
                int soc = [bleModel sos_charge] * 0.1;
                [weakSelf showSocUI:soc];
            }];
        }
    }else{
        [HABleManager bleQuery4GAndGPS:^(HABleModel * _Nonnull bleModel) {
            int gps_signal = [bleModel gps_signal];
            weakSelf.gps_status = gps_signal;
            [weakSelf gps_UI_show:YES];
        }];
    }
}

#pragma mark- notification
- (void)updateCurrentDevice{
    _currentIndex = 0;
    [self.scollView setContentOffset:CGPointMake(0, 0)];
}

-(void)blueVerifySuccess{
    [self bleQueryData];
}

-(void)blueToothDisconnect:(NSNotification *)noti{
    [self showOnlineAndBLEStatusUI];
}

#pragma mark- configUI
-(void)gps_UI_show:(BOOL)show{
    if(show){
        NSString *gps_status_str = self.gps_status ? @"正常": @"异常";
        NSAttributedString *gpsAttrString = [NSAttributedString getAttributeWith:@[gps_status_str] string:[NSString stringWithFormat:@"GPS %@",gps_status_str] Font:Font(12) Color:Color_AAAAAA attributeFont:BFont(12) attributeColor:Color_DDDDDD];
        self.weatherV.gpsLbl.attributedText = gpsAttrString;
        self.weatherV.gps_leading_c.constant = 24;
    }else{
        self.weatherV.gpsLbl.attributedText = nil;
        self.weatherV.gps_leading_c.constant = 0;
    }
   
}

-(void)showSocUI:(int)soc{
    self.percentageView.frame = CGRectMake(2, 2, 25 * soc / 100, 12);
    int prop_val = 20;
    if(self.currentDeviceInfo.additional_props.count > 0){
        NSDictionary *dict = self.currentDeviceInfo.additional_props[0];
        if(dict[@"prop_val"]){
            prop_val = [dict[@"prop_val"] intValue];
        }
    }
    if(soc > prop_val){
        self.percentageView.backgroundColor = Color_7ACC00;
    }else{
        self.percentageView.backgroundColor = Color_F84553;
    }
    NSAttributedString *percentageString = [NSAttributedString getAttributeWith:@[@"%"] string:[NSString stringWithFormat:@"%d%@",soc,@"%"] Font:Font_Light(60) Color:Whire_Color attributeFont:Font_Light(20) attributeColor:Whire_Color];
    self.percentageLbl.attributedText = percentageString;
}

-(void)showBatteryUI:(BOOL)show{
    self.percentageLbl.hidden = !show;
    self.elementimageView.hidden = !show;
}

-(void)showOnlineAndBLEStatusUI{
    if(self.currentDeviceInfo){
        CBPeripheralState state = [HABleManager checkBleConnectedState:self.currentDeviceInfo.sn_code];
        if([self.currentDeviceInfo is4GDevice]){
            if(self.currentDeviceInfo.online_status == 1 && state == CBPeripheralStateConnected){
                self.pointView.hidden = NO;
                self.bleStatusPoint.hidden = NO;
                [_bleStatusPoint mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.offset(0);
                    make.right.offset(10);
                    make.width.height.offset(8);
                }];
            }else if(self.currentDeviceInfo.online_status == 1 && state != CBPeripheralStateConnected){
                self.pointView.hidden = NO;
                self.bleStatusPoint.hidden = YES;
            }else if(self.currentDeviceInfo.online_status == 0 && state == CBPeripheralStateConnected){
                self.pointView.hidden = YES;
                self.bleStatusPoint.hidden = NO;
                [_bleStatusPoint mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.right.top.offset(0);
                    make.width.height.offset(8);
                }];
            }else if(self.currentDeviceInfo.online_status == 0 && state != CBPeripheralStateConnected){
                self.pointView.hidden = YES;
                self.bleStatusPoint.hidden = YES;
            }
        }else{
            [self.bleStatusPoint mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.top.offset(0);
                make.width.height.offset(8);
            }];
            self.bleStatusPoint.hidden = !(state == CBPeripheralStateConnected);
            self.pointView.hidden = YES;
        }
    }else{
        self.pointView.hidden = YES;
        self.bleStatusPoint.hidden = YES;
    }
}


-(void)setViewLayout{
    UIImageView *backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainBack_image"]];
    backImage.frame = CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT);
    backImage.userInteractionEnabled = YES;
    [self.view addSubview:backImage];
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backImageClick)];
    [backImage addGestureRecognizer:imageTap];
    
    {
        _setBtn = [[UIButton alloc] init];
        [self.view addSubview:_setBtn];
        //53
        [_setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(8 + STATUSBAR_HEIGHT);
            make.width.height.offset(40);
            make.right.offset(-24);
        }];
        [_setBtn setImage:[UIImage imageNamed:@"user_setting"] forState:UIControlStateNormal];
        [_setBtn addTarget:self action:@selector(setBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        
        _pointView = [[UIView alloc] init];
        [_setBtn addSubview:_pointView];
        [_pointView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.offset(0);
            make.width.height.offset(8);
        }];
        _pointView.layer.cornerRadius = 4;
        _pointView.clipsToBounds = YES;
        _pointView.backgroundColor = Color_7ACC00;
        _pointView.hidden = YES;
        
        _bleStatusPoint = [[UIView alloc] init];
        [_setBtn addSubview:_bleStatusPoint];
        _bleStatusPoint.layer.cornerRadius = 4;
        _bleStatusPoint.clipsToBounds = YES;
        _bleStatusPoint.backgroundColor = Color_3CB9FF;
        _bleStatusPoint.hidden = YES;
        [_bleStatusPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.right.offset(10);
            make.width.height.offset(8);
        }];
    }
    
    {
        _lineView = [[UIView alloc] init];
        [self.view addSubview:_lineView];
        [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(_setBtn);
            make.width.offset(1);
            make.height.offset(20);
        }];
        _lineView.backgroundColor = rgba(1, 1, 1, 0.4);
        
        _logo = [[UIImageView alloc] init];
        [self.view addSubview:_logo];
        [_logo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_lineView.mas_left).offset(-12);
            make.centerY.equalTo(_setBtn);
            make.width.offset(86);
            make.height.offset(20);
        }];
        _logo.image = [UIImage imageNamed:@"LOGO"];
        _deviceNameLbl = [[UILabel alloc] init];
        [self.view addSubview:_deviceNameLbl];
        [_deviceNameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_lineView.mas_left).offset(12);
            make.centerY.equalTo(_setBtn);
            make.right.equalTo(_setBtn.mas_left).offset(-12);
        }];
        _deviceNameLbl.textColor = Whire_Color;
        _deviceNameLbl.font = Font(24);
    }
    
    {
        _scollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 90 + STATUSBAR_HEIGHT, DEVICE_WIDTH, 480)];
        [self.view addSubview:_scollView];
        _scollView.delegate = self;
        _scollView.backgroundColor = [UIColor clearColor];
        _scollView.showsVerticalScrollIndicator = NO;
        _scollView.showsHorizontalScrollIndicator = NO;
        _scollView.pagingEnabled = YES;
        [_scollView addGestureRecognizer:imageTap];
        _device_NextBtn = [UIButton setButtonWithImage:@"device_Next" cornerRadius:0 backColor:[UIColor clearColor]];
        [self.view addSubview:_device_NextBtn];
        [_device_NextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(0);
            make.width.offset(65);
            make.height.offset(185);
            make.top.equalTo(_scollView.mas_top).offset(90 + (DEVICE_WIDTH - 30 - 190) / 2);
        }];
        [_device_NextBtn addTarget:self action:@selector(next_Device) forControlEvents:UIControlEventTouchUpInside];
        
        _device_LastBtn = [UIButton setButtonWithImage:@"device_Last" cornerRadius:0 backColor:[UIColor clearColor]];
        [self.view addSubview:_device_LastBtn];
        
        [_device_LastBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(0);
            make.width.offset(65);
            make.height.offset(185);
            make.top.equalTo(_scollView.mas_top).offset(90 + (DEVICE_WIDTH - 30 - 190) / 2);
        }];
        [_device_LastBtn addTarget:self action:@selector(last_Device) forControlEvents:UIControlEventTouchUpInside];
        _device_LastBtn.hidden = YES;
    }
    
    self.weatherV = [[[NSBundle mainBundle] loadNibNamed:@"KRWeatherView" owner:self options:nil] lastObject];
    [self.view addSubview:_weatherV];
    [_weatherV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_setBtn.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    {
        _elementimageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Device_element"]];
        [self.view addSubview:_elementimageView];
        [_elementimageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.offset(30);
            make.height.offset(16);
            make.top.equalTo(_weatherV.mas_bottom).offset(17);
        }];
        _percentageView = [[UIView alloc] initWithFrame:CGRectMake(2, 2, 25, 12)];
        [_elementimageView addSubview:_percentageView];
        _percentageView.backgroundColor = Color_7ACC00;
        _percentageLbl = [[UILabel alloc] init];
        [self.view addSubview:_percentageLbl];
        [_percentageLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_percentageView.mas_bottom).offset(8);
            make.centerX.equalTo(self.view);
        }];
    }
}

#pragma mark- button action
- (void)addDevice{
    UserInfo *user = USERINFO;
    if(user.token.length < 1){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    ScanDeviceViewController *vc = [[ScanDeviceViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)setBtnClick{
    if(!_currentDeviceInfo){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆再进行操作"];
    }else{
        DeviceSettingViewController *vc = [[DeviceSettingViewController alloc] init];
        vc.deviceInfo = _currentDeviceInfo;
        _bottomView.deviceInfo = _currentDeviceInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)next_Device{
    _currentIndex++;
    [_scollView setContentOffset:CGPointMake(_currentIndex * DEVICE_WIDTH, 0) animated:YES];
    self.bottomView.isSearch = NO;
    [self.bottomView.searchingIcon.layer removeAllAnimations];
    self.bottomView.searchingIcon.image = [UIImage imageNamed:@"Device_search"];
    [self isShowDeviceNextBtn];
}

- (void)last_Device{
    _currentIndex--;
    [_scollView setContentOffset:CGPointMake(_currentIndex * DEVICE_WIDTH, 0) animated:YES];
    self.bottomView.isSearch = NO;
    [self.bottomView.searchingIcon.layer removeAllAnimations];
    self.bottomView.searchingIcon.image = [UIImage imageNamed:@"Device_search"];
    [self isShowDeviceNextBtn];
}

- (void)xiaokeBtnClick{
    if(_layerView){
        [_layerView removeFromSuperview];
        _layerView = nil;
    }else{
        float imageWidth = (DEVICE_WIDTH - 96 - 64) / 3;
        if(!_isNavBarShow){
            _layerView = [[KRXKAlartView alloc] initWithFrame:CGRectMake(24, DEVICE_HEIGHT - 220 - 82 - (imageWidth + 166) , DEVICE_WIDTH - 48, imageWidth + 156)];
        }else{
            _layerView = [[KRXKAlartView alloc] initWithFrame:CGRectMake(24, DEVICE_HEIGHT - 220 - 82 - (imageWidth + 166) - 70, DEVICE_WIDTH - 48, imageWidth + 156)];
        }
        [self.view addSubview:_layerView];
    }
}
#pragma mark- UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    DDLogInfo(@"=======scrollViewDidEndDecelerating=====");
    float x = scrollView.contentOffset.x + DEVICE_WIDTH /2;
    _currentIndex = x / DEVICE_WIDTH ;
    self.bottomView.isSearch = NO;
    [self.bottomView.searchingIcon.layer removeAllAnimations];
    self.bottomView.searchingIcon.image = [UIImage imageNamed:@"Device_search"];
    [self isShowDeviceNextBtn];
}

#pragma mark- touch UIResponder
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self backImageClick];
}

#pragma mark- touchImageMethod
- (void)backImageClick{
    if(_isAnimate){
        return;
    }
    WEAKSELF
    float imageWidth = (DEVICE_WIDTH - 96 - 64) / 3;
    float width = [[NSStringManager shareInstance] measureSinglelineStringWidth:_alertStr andFont:BFont(12)];
    if(!_isNavBarShow){
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.bottomView.frame = CGRectMake(0, DEVICE_HEIGHT - 220 - 70, DEVICE_WIDTH, 220);
            weakSelf.navBottomView.frame = CGRectMake(0, DEVICE_HEIGHT - 70, DEVICE_WIDTH, 70);
            weakSelf.xiaokeBtn.frame = CGRectMake(DEVICE_WIDTH - 72 - 24, DEVICE_HEIGHT - 220 - 82 - 70, 72, 72);
            weakSelf.layerView.frame = CGRectMake(24, DEVICE_HEIGHT - 220 - 82 - (imageWidth + 166) - 70, DEVICE_WIDTH - 48, imageWidth + 156);
            weakSelf.alertView.frame = CGRectMake(DEVICE_WIDTH - 72 - 24 - width - 25, DEVICE_HEIGHT - 220 - 63 - 70, width + 20, 34);
        } completion:^(BOOL finished) {
            weakSelf.isNavBarShow = YES;
            weakSelf.isAnimate = NO;
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.bottomView.frame = CGRectMake(0, DEVICE_HEIGHT - 220, DEVICE_WIDTH, 220);
            weakSelf.navBottomView.frame = CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, 70);
            weakSelf.xiaokeBtn.frame = CGRectMake(DEVICE_WIDTH - 72 - 24, DEVICE_HEIGHT - 220 - 82, 72, 72);
            weakSelf.layerView.frame = CGRectMake(24, DEVICE_HEIGHT - 220 - 82 - (imageWidth + 166), DEVICE_WIDTH - 48, imageWidth + 156);
            weakSelf.alertView.frame = CGRectMake(DEVICE_WIDTH - 72 - 24 - width - 25, DEVICE_HEIGHT - 220 - 63, width + 20, 34);
        } completion:^(BOOL finished) {
            weakSelf.isNavBarShow = NO;
            weakSelf.isAnimate = NO;
        }];
    }
    weakSelf.isAnimate = YES;
}

#pragma mark: 刷新车辆列表
- (void)updateScollView{
    [_scollView removeAllSubviews];
    if(self.deviceInfoList.count > 0){
        [_logo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_lineView.mas_left).offset(-12);
            make.centerY.equalTo(_setBtn);
            make.width.offset(86);
            make.height.offset(20);
        }];
        _lineView.hidden = NO;
    }else{
        [_logo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(_setBtn);
            make.width.offset(86);
            make.height.offset(20);
        }];
        _deviceNameLbl.text = @"";
        _lineView.hidden = YES;
    }
    for (int i = 0; i < self.deviceInfoList.count + 1; i++) {
        UIView *imageBackView = [[UIView alloc] initWithFrame:CGRectMake(i * DEVICE_WIDTH, 0, DEVICE_WIDTH, 480)];
        [_scollView addSubview:imageBackView];
        UIImageView *deviceImageView = [[UIImageView alloc] init];
        [imageBackView addSubview:deviceImageView];
        imageBackView.clipsToBounds = YES;
        //229  - 133
        if(i == self.deviceInfoList.count){
            [deviceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.offset(0);
                make.left.offset((DEVICE_WIDTH - 480) /2);
                make.width.offset(480);
                make.height.offset(480);
            }];
            deviceImageView.image = [UIImage imageNamed:@"UN_Device"];
            UIButton *addButton = [UIButton setButtonWithImage:@"Device_add" cornerRadius:0 backColor:[UIColor clearColor]];
            [imageBackView addSubview:addButton];
            [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(imageBackView);
                make.width.height.offset(72);
                make.top.offset(208);
            }];
            [addButton addTarget:self action:@selector(addDevice) forControlEvents:UIControlEventTouchUpInside];
            UILabel *tipsLbl = [[UILabel alloc] init];
            [imageBackView addSubview:tipsLbl];
            [tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.view);
                make.top.equalTo(addButton.mas_bottom).offset(24);
            }];
            tipsLbl.font = Font(16);
            tipsLbl.textColor = Whire_Color;
            if(self.deviceInfoList.count > 0){
                tipsLbl.text = @"添加车辆";
            }else{
                tipsLbl.text = @"暂无车辆，请绑定新车辆";
            }
            [self showBatteryUI:NO];
        }else{
            DeviceInfo *info = self.deviceInfoList[i];
            [deviceImageView sd_setImageWithURL:[NSURL URLWithString:info.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
            [deviceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.offset(95);
                make.left.offset(15);
                make.width.offset(DEVICE_WIDTH - 30);
                make.height.offset(DEVICE_WIDTH - 30);
            }];
        }
    }
    _scollView.contentSize = CGSizeMake(DEVICE_WIDTH *(self.deviceInfoList.count + 1), 0);
    [self isShowDeviceNextBtn];
}

#pragma mark:顶部通知消息View
- (void)showMessgeNoticeView{
    _isShowMessgeNoticeView = YES;
    [self.view addSubview:self.noticeView];
    [_noticeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(40);
        make.top.equalTo(self.weatherV.weatherLbl.mas_bottom).offset(6);
        make.left.right.offset(0);
    }];
    [_elementimageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_noticeView.mas_bottom).offset(12);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToShareMessgeVC)];
    [self.noticeView addGestureRecognizer:tap];
}

- (void)goToShareMessgeVC{
    _isShowMessgeNoticeView = NO;
    [_elementimageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.weatherV.mas_bottom).offset(17);
    }];
    [self.noticeView removeAllSubviews];
    [self.noticeView removeFromSuperview];
    self.noticeView = nil;
    KRGarageViewController *vc = [[KRGarageViewController alloc] init];
    vc.type = 2;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)updateDevice{
    [self gps_UI_show:_currentDeviceInfo.deviceConfig.gps];
    if(_currentDeviceInfo){
        [_logo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_lineView.mas_left).offset(-12);
            make.centerY.equalTo(_setBtn);
            make.width.offset(86);
            make.height.offset(20);
        }];
        _lineView.hidden = NO;
        _deviceNameLbl.text = _currentDeviceInfo.device_type_name;
    }else{
        [_logo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(_setBtn);
            make.width.offset(86);
            make.height.offset(20);
        }];
        _deviceNameLbl.text = @"";
        _lineView.hidden = YES;
    }
}

-(void)isShowDeviceNextBtn{
    DDLogInfo(@"=======isShowDeviceNextBtn=====");
    _device_LastBtn.hidden = (_currentIndex == 0);
    _device_NextBtn.hidden = (_currentIndex == self.deviceInfoList.count);
    _currentDeviceInfo = (_currentIndex < self.deviceInfoList.count) ? self.deviceInfoList[_currentIndex] : nil;
    [UserInfoManager sharedInstance].currentDeviceInfo = _currentDeviceInfo;
    [self showBatteryUI:(_currentDeviceInfo && _currentDeviceInfo.battery_type == 1)];
    if(_currentDeviceInfo){
        WEAKSELF
        [KeRenRequestTool deviceConfigQuery:_currentDeviceInfo configResult:^(DeviceConfig * _Nonnull config) {
            weakSelf.currentDeviceInfo.deviceConfig = config;
            weakSelf.bottomView.deviceInfo = weakSelf.currentDeviceInfo;
        }];
    }else{
        self.bottomView.deviceInfo = _currentDeviceInfo;
    }
    UserInfo *user = USERINFO;
    if(user.token.length > 0 && _currentDeviceInfo){
        if([self.currentDeviceInfo is4GDevice]){
            [self getDeviceStatus];
        }
        if(self.currentDeviceInfo.is_manager){
            CBPeripheral *peripheral = [HABleManager checkBleConnectedPeripheral:_currentDeviceInfo.sn_code];
            DDLogInfo(@"=======isShowDeviceNextBtn peripheral is %@,authorized is %@",peripheral,peripheral.authorized);
            if(peripheral){
                if(peripheral.state == CBPeripheralStateConnected){
                    if(peripheral.authorized){
                        [self bleQueryData];
                    }
                }else{
                    DDLogInfo(@"=======bleConnected characteristic is: 07");
                    [KeRenBleTool bleConnected:peripheral callBack:nil];
                }
            }else{
                [self showOnlineAndBLEStatusUI];
                [KeRenBleTool scanAndConnectedBLE:_currentDeviceInfo.sn_code callBack:nil];
            }
        }
    }else{
        [self.bottomView changePowerBtnStatus:NO];
        [self showOnlineAndBLEStatusUI];
    }
    [self updateDevice];    
}

- (void)addKRXKTipsAlertView:(NSString *)alertStr{
    [_alertView removeFromSuperview];
    _alertStr = alertStr;
    float width = [[NSStringManager shareInstance] measureSinglelineStringWidth:alertStr andFont:BFont(12)];
    _alertView = [[KRXKTipsAlertView alloc] initWithFrame:CGRectMake(DEVICE_WIDTH - 72 - 24 - width - 25, _xiaokeBtn.frame.origin.y + 19, width + 20, 34) tips:alertStr];
    [self.view addSubview:_alertView];
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.alertView removeFromSuperview];
    });
}

- (void)invalidateTimer{
    if(_timer){
        [_timer invalidate];
        _timer = nil;
    }
}


@end
